package com.paradigmcreatives.game.manager;

import java.io.IOException;

import com.paradigmcreatives.game.R;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;

import com.example.flip3d.DisplayNextView;
import com.example.flip3d.Flip3dAnimation;
import com.paradigmcreatives.game.DoodleGameActivity;
import com.paradigmcreatives.game.listeners.KeyWordKeyListener;
import com.paradigmcreatives.game.prefs.Preferences;
import com.paradigmcreatives.game.runtime.RuntimeData;
import com.paradigmcreatives.game.timers.DrawTimer;
import com.paradigmcreatives.game.ui.CustomTimer;

public class UIManager implements IDoodleManager{

	private DoodleGameActivity doodleGameActivity = null;

	private static String TAG = "UIManager";

	private static UIManager uiManager = null;

	private Animation fadeIn;
	private Animation fadeOut;

	public enum AppStates {
		INIT,
		WORD_ENTERED,
		STARTED_DRAWING,
		INTERRUPT
	};

	public AppStates appState = AppStates.INIT;

	public static UIManager getInstance(DoodleGameActivity doodleGameActivity) {
		Log.i(TAG, "Initiating UIManager");
		if(uiManager == null){
			uiManager = new UIManager(doodleGameActivity);
		}

		return uiManager;
	}

	private UIManager(DoodleGameActivity doodleGameActivity){
		this.doodleGameActivity = doodleGameActivity;
		fadeIn = AnimationUtils.loadAnimation(doodleGameActivity, android.R.anim.fade_in);
		fadeOut = AnimationUtils.loadAnimation(doodleGameActivity, android.R.anim.fade_out);
		fadeIn.setDuration(200);
		fadeOut.setDuration(200);

		
	}

	public void setUpListenersForUiElements(){

		if(doodleGameActivity != null){
			Log.i(TAG, "Setting up listerners for UI elements");

			doodleGameActivity.keywordInput.setOnKeyListener(new KeyWordKeyListener(doodleGameActivity));
			doodleGameActivity.keywordGuess.setOnKeyListener(new KeyWordKeyListener(doodleGameActivity));

			doodleGameActivity.doodleCanvas.registerToListen(getInstance(doodleGameActivity));

			doodleGameActivity.nextTurn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					revealKeyword();
				}
			});
		}
	}

	@Override
	public void WordEntered(String wordEntered) {
		Log.i(TAG, "WordEntered by user " + wordEntered);
		appState = AppStates.WORD_ENTERED;
		RuntimeData.keywordEntered = wordEntered.trim();
		doodleGameActivity.doodleCanvas.setEnableDrawing(true);
		doodleGameActivity.keywordInput.setText(wordEntered);
		doodleGameActivity.keywordInput.setFocusable(false);
		doodleGameActivity.keywordInput.setEnabled(false);
		DrawTimer.getInstance();
	}

	@Override
	public void startedDrawing() {
		Log.i(TAG, "User Started Drawing ");
		appState = AppStates.STARTED_DRAWING;
	
		DrawTimer.getInstance().startTicking(uiManager, 1000);
		final CustomTimer customTimer = new CustomTimer(doodleGameActivity, Preferences.doodleDrawTime, doodleGameActivity.face1.getWidth(), doodleGameActivity.face1.getHeight());
		doodleGameActivity.face2.addView(customTimer);
		customTimer.bringToFront();
		Animation waveScale = AnimationUtils.loadAnimation(doodleGameActivity, R.anim.wave_scale);
		waveScale.setDuration(500);
		waveScale.setRepeatMode(Animation.REVERSE);
		waveScale.setRepeatCount(Animation.INFINITE);
		customTimer.startAnimation(waveScale);
		
		customTimer.startDisplayingProgress(new Handler(){
			
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if(msg.what == 101){
					Log.i(TAG, "Received message in handler to remove timer");
					
					   MediaPlayer player = MediaPlayer.create(doodleGameActivity, R.raw.bell);
					    try {
							player.prepare();
						} catch (IllegalStateException e) {

							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						
					    player.start();
					    ((Vibrator)doodleGameActivity.getSystemService(doodleGameActivity.VIBRATOR_SERVICE)).vibrate(300);
					 customTimer.clearAnimation();
					doodleGameActivity.face2.removeView(customTimer);
				}
			}
		});
		swapViewsInBottombar(doodleGameActivity.face1,doodleGameActivity.face2);
	}

	private void swapViewsInBottombar(RelativeLayout face1,RelativeLayout face2) {

		if(face1.getVisibility() == View.VISIBLE){
			applyRotation(0, 90, face1, face2, true);
		}else{
			applyRotation(0, -90, face1, face2, false);
		}
	}

	@Override
	public void drawingTimeUp() {
		appState = AppStates.INTERRUPT;
		Log.i(TAG, "Interrupted by timer");
		doodleGameActivity.doodleCanvas.setEnableDrawing(false);
	}

	@Override
	public void guessedKeyword(boolean isGuessedCorrect) {
		Log.i(TAG, "Guessed !! " + isGuessedCorrect);
		if(isGuessedCorrect){
			doodleGameActivity.keywordGuess.setBackgroundColor(Color.GREEN);
			restartApp();
/*			try {
				Thread.sleep(2000);
				restartApp();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}*/
		}else{
			doodleGameActivity.keywordGuess.setText("");
			swapViewsInBottombar(doodleGameActivity.face2, doodleGameActivity.face3);
		}

	}

	@Override
	public void revealKeyword() {

		swapViewsInBottombar(doodleGameActivity.face3, doodleGameActivity.face1);
		
		doodleGameActivity.doodleCanvas.setEnableDrawing(true);
	}


	private void applyRotation(float start, float end,RelativeLayout face1,RelativeLayout face2,boolean isFirstView) {
		// Find the center of image
		final float centerX = face1.getWidth() / 2.0f;
		final float centerY = face2.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Flip3dAnimation rotation =
				new Flip3dAnimation(start, end, centerX, centerY);
		rotation.setDuration(500);
		rotation.setStartOffset(700);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(isFirstView, face1, face2));

		if (isFirstView)
		{
			face1.startAnimation(rotation);
		} else {
			face2.startAnimation(rotation);
		}
		face2.bringToFront();

	}

	@Override
	public void restartApp() {
		Intent intent = doodleGameActivity.getIntent();
		doodleGameActivity.finish();
		doodleGameActivity.startActivity(intent);
		doodleGameActivity.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

	}

	@Override
	public void isDrawing(final boolean drawing) {
		doodleGameActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {



				if(drawing){
					doodleGameActivity.colorPalatte.startAnimation(fadeOut);
					fadeOut.setAnimationListener(new AnimationListener() {

						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationEnd(Animation animation) {
							// TODO Auto-generated method stub
							doodleGameActivity.colorPalatte.setVisibility(View.GONE);
						}
					});
				}else{
					doodleGameActivity.colorPalatte.startAnimation(fadeIn);
					fadeIn.setAnimationListener(new AnimationListener() {

						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationEnd(Animation animation) {
							// TODO Auto-generated method stub
							doodleGameActivity.colorPalatte.setVisibility(View.VISIBLE);
						}
					});
				}
			}
		});
	}

	public void unRegisterAllListeners() {
	
		if(doodleGameActivity != null){
			Log.i(TAG, "Un registering listerners for UI elements");

			doodleGameActivity.keywordInput.setOnKeyListener(null);
			doodleGameActivity.keywordGuess.setOnKeyListener(null);

			doodleGameActivity.doodleCanvas.registerToListen(null);

		}
	}





}
